package cn.zyq.ykb.system.cos;


import cn.hutool.core.util.IdUtil;

import cn.zyq.ykb.beans.admin.Admin;
import cn.zyq.ykb.beans.file.FileStorage;
import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.service.file.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Slf4j
public class CosService {
	@Autowired
	private FileStorageService fileStorageService;


	private String active;
	private cos cos;



	public String getActive() {
		return active;
	}

	public void setActive(String active) {
		this.active = active;
	}

	public cos getStorage() {
		return cos;
	}

	public void setStorage(cos cos) {
		this.cos = cos;
	}

	/**
	 * 存储一个文件对象
	 *
	 * @param inputStream
	 *            文件输入流
	 * @param contentLength
	 *            文件长度
	 * @param contentType
	 *            文件类型
	 * @param fileName
	 *            文件索引名
	 */
	public FileStorage store(InputStream inputStream, long contentLength, String contentType, String fileName) {
		String key = generateKey(fileName);
		log.info("文件存储key：" + key);
		cos.store(inputStream, contentLength, contentType, key);

		String url = generateUrl(key);
        log.info("文件存储url：" + url);
		FileStorage storageInfo = new FileStorage();
		storageInfo.setName(fileName);
		storageInfo.setSize((int) contentLength);
		storageInfo.setType(contentType);
		storageInfo.setKey(key);
		storageInfo.setUrl(url);
		fileStorageService.add(storageInfo, new SysAdmin());
		return storageInfo;
	}

	private String generateKey(String originalFilename) {
		int index = originalFilename.lastIndexOf('.');
		String suffix = originalFilename.substring(index);
		String key = null;
		String s = IdUtil.fastSimpleUUID();
		key = s.substring(0,20) + suffix;
		return key;
	}

	public Stream<Path> loadAll() {
		return cos.loadAll();
	}

	public Path load(String keyName) {
		return cos.load(keyName);
	}

	public Resource loadAsResource(String keyName) {
		return cos.loadAsResource(keyName);
	}

	public void delete(String keyName) {
		cos.delete(keyName);
	}

	private String generateUrl(String keyName) {
		return cos.generateUrl(keyName);
	}

	public String upt(String originalFilename) {
		String key = generateKey(originalFilename);
		log.info("文件存储key：" + key);
		return key;
	}
}
